from flask import render_template, g, current_app, jsonify, abort, request

from info import db
from info.models import News, Comment, CommentLike
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import news_blu


@news_blu.route('/comment_like', methods=['POST'])
@user_login_data
def user_comment_list():
    # "comment_id": comment_id,
    # "action": action,
    # "news_id": news_id
    if not g.user:
        return jsonify(errno=RET.NODATA, errmsg="用户未登陆")
    data_dict = request.json
    comment_id = data_dict.get('comment_id')
    action = data_dict.get('action')
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    if action not in ['add', 'remove']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数格式错误")
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="评论查询失败")
    if not comment:
        return jsonify(errno=RET.DATAERR, errmsg="评论不存在")
    try:
        if action == 'add':
            comment_like_list = CommentLike.query.filter(CommentLike.user_id == g.user.id,
                                                         CommentLike.comment_id == comment_id).first()
            if not comment_like_list:
                comment_like = CommentLike()
                comment_like.comment_id = comment_id
                comment_like.user_id = g.user.id
                comment.like_count += 1
                db.session.add(comment_like)
                db.session.commit()
        else:
            comment_like_list = CommentLike.query.filter(CommentLike.user_id == g.user.id,
                                                         CommentLike.comment_id == comment_id).first()
            if comment_like_list:
                db.session.delete(comment_like_list)
                comment.like_count -= 1
                db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route('/<int:news_id>')
@user_login_data
def get_detail(news_id):
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻查询失败")
    if not news:
        abort(404)
    news.clicks += 1
    try:
        news_items = News.query.order_by(News.clicks.desc()).limit(8)
    except Exception as e:
        current_app.logger.error(e)
    clicks_news_list = []
    for item in news_items:
        clicks_news_list.append(item.to_dict())
    is_collected = False
    if g.user and news in g.user.collection_news:
        is_collected = True
    try:
        comments = Comment.query.filter(Comment.news_id == news.id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取评论失败")
    comments_id_list = [comment.id for comment in comments]
    comments_like_list = CommentLike.query.filter(CommentLike.comment_id.in_(comments_id_list),
                                                  CommentLike.user_id == g.user.id).all()
    comments_like_ids = [comment_like.comment_id for comment_like in comments_like_list]
    comment_list = []
    for comment in comments:
        comm_dict = comment.to_dict()
        comm_dict["is_like"] = False
        if g.user and comment.id in comments_like_ids:
            comm_dict["is_like"] = True
        comment_list.append(comm_dict)
    data = {
        "user_info": g.user.to_dict() if g.user else "",
        "news": news.to_dict(),
        'clicks_news_list': clicks_news_list,
        'is_collected': is_collected,
        'comments': comment_list
    }
    return render_template('news/detail.html', data=data)


@news_blu.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    if not g.user:
        return jsonify(errno=RET.NODATA, errmsg="用户未登陆")
    data_dict = request.json
    news_id = data_dict.get('news_id')
    action = data_dict.get('action')
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数格式错误")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻查询失败")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="该新闻不存在")
    try:
        if action == 'collect':
            g.user.collection_news.append(news)
        else:
            g.user.collection_news.remove(news)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="操作收藏列表失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    if not g.user:
        return jsonify(errno=RET.NODATA, errmsg="用户未登陆")
    data_dict = request.json
    news_id = data_dict.get('news_id')
    content = data_dict.get('comment')
    parent_id = data_dict.get('parent_id')
    if not all([news_id, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻查询失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="该新闻不存在")
    comment = Comment()
    comment.user_id = g.user.id
    comment.news_id = news.id
    comment.content = content
    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库添加评论失败")
    return jsonify(errno=RET.OK, errmsg="添加评论成功", data=comment.to_dict())
